﻿using AbpApplication.InPut;
using Azure;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Tools.Converter;
using HandyControl.Tools.Extension;
using Microsoft.AspNetCore.SignalR.Client;
using NewWms.Apiservice;
using NewWms.Apiservice.Dto;
using NewWms.Apiservice.InPut;
using NewWms.Extend;
using NewWms.Views;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Reconstruct_Desktop.Apiservice;
using Reconstruct_Desktop.Apiservice.Dto;
using SingalR.Client;
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Windows;
using WcsZz.Extend;
using wms_wpf;
using wms_wpf.Apiservice;
using wms_wpf.Extend;
using wms_wpf.InPut;
using MessageBox = HandyControl.Controls.MessageBox;

namespace NewWms.ViewModels
{
    public partial class UpAndDownShelvesViewModel : BindableBase, INavigationAware
    {
        //define
        private readonly IBaseService_Client baseService;
        private readonly IViewService_Client viewService;
        private readonly IEssService_Client essService;
        private readonly ICustomService_Client customService;
        public UpAndDownShelvesViewModel(UpAndDownShelvesView upAndDownShelvesView)
        {

            baseService = new BaseService_Client();
            viewService = new ViewService_Client();
            essService = new EssService_Client();
            customService = new CustomService_Client();
            UpAndDownShelvesView = upAndDownShelvesView;
            InPut_BaseService7 = new InPut_BaseService7_Client();
            InPut_BaseService6 = new InPut_BaseService6_Client();
            InPut_BaseService4 = new InPut_BaseService4_Client();
            InPut_ViewService4 = new InPut_ViewService4_Client();
            InPut_ViewService10 = new InPut_ViewService10_Client();
            inPut_BaseService19 = new InPut_BaseService19_Client();
            View_MaterialDtos = new List<View_MaterialDto>();
            View_TaskOrderDtos = new List<View_TaskOrderDto>();
            InlethouseModels = new List<InlethouseLineDto>();
            Command = new DelegateCommand<string>(Method);

            View_TaskOrder();
            GetCanves();
            GetHubConnectionAsync();
            EventAggregatorHelper.EventAggregator.ResgiterMessage(arg =>
            {
                CreateMaterialBase();
            }, "新增物料");
            EventAggregatorHelper.EventAggregator.ResgiterMessage(arg =>
            {
                DeleteMaterial();
            }, "删除物料");
            EventAggregatorHelper.EventAggregator.ResgiterMessage(arg =>
            {
                View_MaterialDto();
            }, "刷新页面");
            EventAggregatorHelper.EventAggregator.ResgiterMessage(arg =>
            {
                View_NeetOutMaterial();
            }, "获取物料");
            this.customService = customService;
        }
        private readonly UpAndDownShelvesView UpAndDownShelvesView;
        private InPut_BaseService7_Client inPut_BaseService7;
        public InPut_BaseService7_Client InPut_BaseService7
        {
            get { return inPut_BaseService7; }
            set { inPut_BaseService7 = value;RaisePropertyChanged(); }
        }
        private InPut_BaseService6_Client inPut_BaseService6;
        public InPut_BaseService6_Client InPut_BaseService6
        {
            get { return inPut_BaseService6; }
            set { inPut_BaseService6 = value;RaisePropertyChanged();}
        }
        private InPut_ViewService10_Client inPut_ViewService10;
        public InPut_ViewService10_Client InPut_ViewService10
        {
            get { return inPut_ViewService10; }
            set { inPut_ViewService10 = value;RaisePropertyChanged(); }
        }
        private InPut_ViewService4_Client inPut_ViewService4;
        public InPut_ViewService4_Client InPut_ViewService4
        {
            get { return inPut_ViewService4; }
            set { inPut_ViewService4 = value;RaisePropertyChanged(); }
        }
        private List<View_MaterialDto> view_MaterialDtos;
        public List<View_MaterialDto> View_MaterialDtos
        {
            get { return view_MaterialDtos; }
            set { view_MaterialDtos = value; RaisePropertyChanged(); }
        }
        private List<View_TaskOrderDto> view_TaskOrderDtos;
        public List<View_TaskOrderDto> View_TaskOrderDtos
        {
            get { return view_TaskOrderDtos; }
            set { view_TaskOrderDtos = value;RaisePropertyChanged();}
        }
        private ObservableCollection<View_NeetOutMaterialDto> view_NeetOutMaterialDtos;
        public ObservableCollection<View_NeetOutMaterialDto> View_NeetOutMaterialDtos
        {
            get { return view_NeetOutMaterialDtos; }
            set { view_NeetOutMaterialDtos = value; RaisePropertyChanged(); }
        }

        private List<View_SowingWallLineDto> view_SowingWallLineDtos;
        public List<View_SowingWallLineDto> View_SowingWallLineDtos
        {
            get { return view_SowingWallLineDtos; }
            set { view_SowingWallLineDtos = value;RaisePropertyChanged(); }
        }


        private InPut_BaseService19_Client inPut_BaseService19;
        public InPut_BaseService19_Client InPut_BaseService19
        {
            get { return inPut_BaseService19; }
            set { inPut_BaseService19 = value; RaisePropertyChanged(); }
        }


        private List<InlethouseLineDto> inlethouseModels;

        public List<InlethouseLineDto> InlethouseModels
        {
            get { return inlethouseModels; }
            set { inlethouseModels = value; RaisePropertyChanged(); }
        }

        private string materialcode;
        public string MaterialCode
        {
            get { return materialcode; }
            set { materialcode = value; RaisePropertyChanged(); }
        }
        private string boxcode;
        [MinLength(10)]
        public string BoxCode
        {
            get { return boxcode; }
            set { boxcode = value; RaisePropertyChanged(); }
        }
  
        private string boxgridcode;
        public string BoxGridCode
        {
            get { return boxgridcode; }
            set { boxgridcode = value; RaisePropertyChanged(); }
        }
        private string quantity;
        public string Quantity
        {
            get { return quantity; }
            set { quantity = value;RaisePropertyChanged(); }
        }
        private string viewDelQuantity;
        public string ViewDelQuantity
        {
            get { return viewDelQuantity; }
            set { viewDelQuantity = value;RaisePropertyChanged(); }
        }
        private InPut_BaseService4_Client inPut_BaseService4;
        public InPut_BaseService4_Client InPut_BaseService4
        {
            get { return inPut_BaseService4; }
            set { inPut_BaseService4 = value;RaisePropertyChanged(); }
        }
        private bool _isSubmitting=true;
        public bool IsSubmitting 
        {
            get { return _isSubmitting; }
            set { _isSubmitting = value; RaisePropertyChanged(); }
        }
        public DelegateCommand<string> Command { get; set; }

        //更换料盒
        [RelayCommand]
        public async void UpdateBoxMaterial()
        {
            bool Nullres = InPut_BaseService7.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService7) != null);
            if (!Nullres) { MessageBox.Info("请输入完整"); return; }
            bool res = await baseService.UpdateBoxMaterial(InPut_BaseService7);
            if (res)
            {
                View_MaterialDto();
                InPut_BaseService7.Consumer_MaterialId = null;
                InPut_BaseService7.BoxPositionCode = null;
            }
        }

        //功能
        public void Method(string obj)
        {
            switch (obj)
            {
                case "CreateMaterialBase": CreateMaterialBase(); break;
                case "View_BoxGrid_Material": break;
                case "DeleteBoxs": break;
                case "CreateTaskOrder": CreateTaskOrder(); break;
                case "View_TaskOrder":
                    View_TaskOrder();break;
                case "DeleteMaterial":
                    DeleteMaterial();break;
                case "View_NeetOutMaterial":
                    View_NeetOutMaterial(); break;


            }
        }
        //新增物料
        private async void CreateMaterialBase()
        {

            bool Nullres = InPut_BaseService7.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService7) != null);
            if (!Nullres) { MessageBox.Info("请输入完整"); return; }
            bool res = await baseService.CreateMaterialBase(InPut_BaseService7);
            if (res)
            {
                View_MaterialDto();
                InPut_BaseService7.Consumer_MaterialId = null;
                InPut_BaseService7.BoxPositionCode = null;
            }           
          
        }
        //更新数量
        [RelayCommand]
        private async  void UpdateMaterialBaserQuantity()
        {

      
        }
        //出库上架任务
        [RelayCommand]
        private async void CreateTaskOrder_Outbound()
        {
            InPut_BaseService6.BoxCode = InPut_BaseService4.BoxPositionCode;
            BoxCode= InPut_BaseService4.BoxPositionCode;
            inPut_BaseService6.InletCode = GlobalVariable.OutletCode;
            InPut_BaseService6.Machine = int.Parse(GlobalVariable.Machine);
            bool Nullres = InPut_BaseService6.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService6) != null);
            if (!Nullres) { MessageBox.Info("请检查箱号和入库口"); return; }
            Tuple<bool, string> CreateTaskOrder_tuple = await baseService.CreateTaskOrder(InPut_BaseService6);
            if (CreateTaskOrder_tuple.Item1)
            {
                GetCanves();
                if (!CreateTaskOrder_tuple.Item2.Contains("移动"))
                {
                    movecontainer($"上架-{GlobalVariable.Machine}");
                }
           
                //发送任务
                bool res = await View_TaskOrder();
                if (res)
                {
                    TaskToEss(View_TaskOrderDtos);
                }
                BoxCode = "";
                InPut_BaseService4.BoxPositionCode = "";
            }
        }
        //新增Agv入库任务
        private async void CreateTaskOrder()
        {
            //BarTenderPrint.Label("View_NeetOutMaterialDto.MaterialCode",
            //         "View_NeetOutMaterialDto.MaterialName", "View_NeetOutMaterialDto.Batch",
            //         "View_NeetOutMaterialDto.NeetQuantity.ToString()", "View_NeetOutMaterialDto.Unit",
            //         "View_NeetOutMaterialDto.OrderNo", "View_NeetOutMaterialDto.Consumer_MaterialId");
            InPut_BaseService6.BoxCode = BoxCode;
            inPut_BaseService6.InletCode = GlobalVariable.OutletCode;
            InPut_BaseService6.Machine = int.Parse(GlobalVariable.Machine);
            bool Nullres = InPut_BaseService6.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService6) != null);
            if (!Nullres) { MessageBox.Info("请检查箱号和入库口"); return; }
            Tuple<bool, string> CreateTaskOrder_tuple = await baseService.CreateTaskOrder(InPut_BaseService6);
            if (CreateTaskOrder_tuple.Item1)
            {

                GetCanves();
                if (!CreateTaskOrder_tuple.Item2.Contains("移动"))
                {
                    movecontainer($"上架-{GlobalVariable.Machine}");
                }

                BoxCode = "";
                //发送任务
                bool res = await View_TaskOrder();
                if (res)
                {
                    TaskToEss(View_TaskOrderDtos);
                }
            }
        }
        //删除agv任务
        [RelayCommand]
        private async void DeleteTaskOrder(IList SelectItems)
        {

            List<string> InPut = new List<string>();
            foreach (View_TaskOrderDto item in SelectItems)
            {
                InPut.Add(item.TaskOrderCode);
            }
            bool res = await baseService.DeleteTaskOrder(InPut);
            if (res) View_TaskOrder();
            GetCanves();
    
          

        }
        //取料确认
        private async void DeleteMaterial()
        {

            InPut_BaseService4.Machine = GlobalVariable.Machine;
            bool Nullres = InPut_BaseService4.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService4) != null);

            if (!Nullres) { MessageBox.Info("请输入完整"); return; }
            Tuple<bool, string, string> ResTuple = await baseService.DeleteMaterial(InPut_BaseService4);
            if (ResTuple.Item1)
            {
                ViewDelQuantity = $"请从{ResTuple.Item2}拿走";
                await View_NeetOutMaterial();
                await GetCanves();
                try
                {
                    await baseService.SendCustomerOutRep(ResTuple.Item3);
                }
                catch (Exception ex)
                {
                    await baseService.CreateLog("测试SendCustomerOutRep", ex.ToString());
                }
                await baseService.CreateLog("测试", $"测试1{InPut_BaseService4.Consumer_MaterialId}");
                try
                {
                    await baseService.CheckBoxMaterial(InPut_BaseService4.BoxPositionCode);
                }
                catch (Exception ex)
                {
                    await baseService.CreateLog("测试CheckBoxMaterial", ex.ToString());
                }
            }
            await baseService.CreateLog("测试", $"测试2{InPut_BaseService4.Consumer_MaterialId}");
            InPut_BaseService4.Consumer_MaterialId = "";
        }
        //删物料
        [RelayCommand]
        private async void ReMovesMaterial(IList SelectItems)
        {
           MessageBoxResult messageBoxResult= HandyControl.Controls.MessageBox.Show("确认删除","提示",MessageBoxButton.YesNo);
            if (messageBoxResult != MessageBoxResult.Yes)
            {
                return;
            }
            List<string> InPut = new List<string>();
            foreach (View_MaterialDto item in SelectItems)
            {
                InPut.Add(item.MaterialCode);
            }
            bool res = await baseService.RemovesMaterial(InPut);
            if (res) View_MaterialDto();
        }
        //发送任务
        [RelayCommand]
        private async void TaskToEss(IList SelectItems)
        {
           
            try
            {
                IsSubmitting = false;
                foreach (View_TaskOrderDto item in SelectItems)
                {

                    if (item.State == "已下发") continue;
                    Ess_Input_Client ess_Input = new Ess_Input_Client();
                    ess_Input.taskType = "putaway";
                    ess_Input.taskGroupCode = $"taskGroupCode-{item.groupPriority}";
                    ess_Input.groupPriority = item.groupPriority;
                    List<Tasks> data = new List<Tasks>();
                    Tasks ta = new Tasks();
                    ta.taskCode = item.TaskOrderCode;
                    ta.taskPriority = item.taskPriority;
                    data.Add(ta);
                    ess_Input.tasks = data;
                    TaskDescribe td = new TaskDescribe();
                    td.containerCode = item.BoxCode;
                    td.containerType = "CT_KUBOT_STANDARD";
                    td.storageTag = "";
                    td.fromLocationCode = "";//item.InlethouseCode
                    td.toLocationCode = item.WarehouseCode;
                    td.toStationCode = "haiport_station_1";
                    td.isPutaway = false;
                    ta.taskDescribe = td;
                    string res = await essService.CreateTask(ess_Input);

                    if (res.Contains("OK"))
                    {
                        InPut_BaseService11_Client inPut = new InPut_BaseService11_Client();
                        inPut.TaskOrderCode = item.TaskOrderCode;
                        inPut.State= "已下发";
                        inPut.IsSend = true;
                        await baseService.UpdateTaskOrderState(inPut);
                        await baseService.CreateLog("上架", item.BoxCode + "-" + item.WarehouseCode);
                    }
                }
                View_TaskOrder();
            }
            catch (Exception ex)
            {
         
                LognetHelper.WriteLog("异常闪退:*-", ex);
            }
            finally
            {
                IsSubmitting=true;
            }
    
        }
        //箱盒视图
        private async void View_MaterialDto()
        {
            InPut_ViewService4.PageIndex = 1;
            InPut_ViewService4.PageSize = 100;
            InPut_ViewService4.BoxPositionCode= InPut_BaseService7.BoxPositionCode;
            Tuple<List<View_MaterialDto>, long?, long?>tuple= await  viewService.View_Material(InPut_ViewService4);
            if (tuple.Item1 != null)
            {
                View_MaterialDtos=tuple.Item1;
            }
        }
        //任务视图
        private async Task<bool> View_TaskOrder()
        {

            InPut_ViewService5_Client inPut_ViewService5 = new InPut_ViewService5_Client();
            inPut_ViewService5.PageIndex = 1;
            inPut_ViewService5.PageSize = 50;
            inPut_ViewService5.Type = "入库";
            inPut_ViewService5.State = "未下发";
            inPut_ViewService5.Machine = int.Parse(GlobalVariable.Machine);

            Tuple<List<View_TaskOrderDto>, long?, long?> tuple = await viewService.View_TaskOrder(inPut_ViewService5);
            if (tuple != null)
            {
                View_TaskOrderDtos = tuple.Item1;
                return true;
            }
            return false;
        }
        //出料视图
        private async Task View_NeetOutMaterial()
        {
            InPut_ViewService10.PageIndex = 1;
            InPut_ViewService10.PageSize = 50;
            InPut_ViewService10.Machine = GlobalVariable.Machine;
            inPut_ViewService10.BoxCode = InPut_BaseService4.BoxPositionCode;
            Tuple<ObservableCollection<View_NeetOutMaterialDto>, long?, long?> tuple = await viewService.View_NeetOutMaterial(InPut_ViewService10);
            if (tuple != null)
            {
                View_NeetOutMaterialDtos= tuple.Item1;
            }
        }
        //输送线滚动
        [RelayCommand]
        private async void movecontainer(string? obj)
        {
            if(string.IsNullOrEmpty(BoxCode))
            {
                MessageBox.Info("请输入箱号");
                return;
            }
            string slotCode = "";
            string direction = "";
            if (obj == "上架-1")
            {
                if (GlobalVariable.Machine != "1")
                {
                    MessageBox.Info("拣料台错误");
                    return;
                }
                slotCode = "1-4";
                direction = "3";

            }
            if (obj == "上架-2")
            {
                if (GlobalVariable.Machine != "2")
                {
                    MessageBox.Info("拣料台错误");
                    return;
                }
                slotCode = "1-5";
                direction = "3";
            }
            if (obj == "下架-1")
            {
                if (GlobalVariable.Machine != "1")
                {
                    MessageBox.Info("拣料台错误");
                    return;
                }
                slotCode = "1-2";
                direction = "1";
            }
            if (obj == "下架-2")
            {
                if (GlobalVariable.Machine != "2")
                {
                    MessageBox.Info("拣料台错误");
                    return;
                }
                slotCode = "1-2";
                direction = "2";
            }
            if (obj == "移位-2")
            {
                if (GlobalVariable.Machine != "1")
                {
                    MessageBox.Info("拣料台错误");
                    return;
                }
                slotCode = "1-4";
                direction = "2";
            }
            if (obj == "移位-1")
            {
                if (GlobalVariable.Machine != "2")
                {
                    MessageBox.Info("拣料台错误");
                    return;
                }
                slotCode = "1-5";
                direction = "1";
            }
            await baseService.moveContainer_wms(slotCode,direction,obj,BoxCode);
        }
        //缓存区图形
        private async Task GetCanves()
        {
            View_SowingWallLineDtos= await viewService.View_SowingWallLine(GlobalVariable.Machine);
        }
        //signalr
        public async Task GetHubConnectionAsync()
        {
            HubConnection hubConnection = await SingalrMethod.GetConnectionToWmsAsync();
            hubConnection.On<string,string,string>("CallByHub", async (string token,string boxcode,string machine) =>
            {
              await GetCanves();  
            });
        }
        //修改出库数量
        [RelayCommand]
        public async Task UpdateNeetQuantity(Guid Id_NeetOutMaterial)
        {
            InPut_BaseService19.Id_NeetOutMaterial = Id_NeetOutMaterial;
           bool res=  await baseService.UpdateNeetQuantity(InPut_BaseService19);
            if (res)
            {
                View_NeetOutMaterial();
            }
        }
        //删除输送线任务
        [RelayCommand]
        public async Task DeleteMoveContainer()
        { 
            if (string.IsNullOrEmpty(BoxCode))
            {
                MessageBox.Info("请输入箱号");
                return;
            }
            bool res= await baseService.DeleteMoveContainer(BoxCode);
        
        }
        //更新播种墙状态
        [RelayCommand]
        private async void Update_SowingWall(string obj)
        {
            bool res= await baseService.Update_SowingWall(obj);
            if (res)
            {
               await GetCanves();
            }
        }
        //修改手动出库数量
        [RelayCommand]
        private async void UpdateMaterialQuantity(View_MaterialDto Dto)
        {
            bool boolres = double.TryParse(Dto.Quantity.HasValue ? Dto.Quantity.Value.ToString() : null, out _);//_什么意思
            if (!boolres)
            {
                Growl.Info("请输入数字", "msg");
                View_MaterialDto();
                return;
            }
            InPut_BaseService25_Client inPut_BaseService25_Client = new InPut_BaseService25_Client();
            inPut_BaseService25_Client.Id_Materialbase = Dto.Id_Materialbase;
            inPut_BaseService25_Client.Quantity = (double)Dto.Quantity;
            bool res = await baseService.UpdateMaterialQuantity(inPut_BaseService25_Client);
            if (!res)
            {
                View_MaterialDto();
            }
        }
        //故障处理
        [RelayCommand]
        private async void Update_Error()
        {

            MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Info("注意:请确认料盒已下架");
            if (messageBoxResult != MessageBoxResult.OK)
            {
                return;
            }
            if (string.IsNullOrEmpty(BoxCode))
            {
                MessageBox.Show("请输出箱号");
                return;
            }
            Tuple<bool,string> tuple=  await baseService.GetOrderNo(BoxCode);
            if (tuple.Item1)
            {
                InPut_EssService inPut_EssService = new InPut_EssService();
                inPut_EssService.taskCode = tuple.Item2;
                inPut_EssService.containerCode = BoxCode;
                inPut_EssService.eventType = "task";
                inPut_EssService.status = "success";
                bool res=   await baseService.TaskStatusChange(inPut_EssService);
                if (res)
                {
                    await baseService.CreateLog("故障清除", $"单号{inPut_EssService.taskCode}箱号{BoxCode}");
                }
            }
        }

        //主页设置
        private string title = "物料上下架";
        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        public async void OnNavigatedFrom(NavigationContext navigationContext)
        {
            
        }
        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            View_TaskOrder();
            InPut_ViewService4.PageIndex = 1;
            InPut_ViewService4.PageSize = 200;
            GetCanves();

        }
    }
}
